import axios from 'axios'
import { Notification } from 'element-ui'
import { throwErr } from './throwErr'
// const server = 'http://delaicloud.com:28020/lockerApi'
const server = 'http://delaicloud.com:28003/locker'
// const server = 'http://192.168.0.154:28003/locker'
//过滤请求
axios.interceptors.request.use(config => {
  let token = JSON.parse(localStorage.getItem('userInfo')) ? JSON.parse(localStorage.getItem('userInfo')).token : ''
  config.timeout = 20 * 1000 //请求响应时间
  config.headers['Content-Type'] = 'application/json'
  config.headers.langCode =  'en'
  if (token) {
    config.headers.token = token

  }
  return config
}, error => {
  return Promise.reject(error)
})
// 添加响应拦截器
axios.interceptors.response.use(
  response => {
    if (response.data.code === 200) {
      return Promise.resolve(response.data.data)
    } else {
      Notification({ type: 'error', title: 'error', message: response.data.msg || 'error' })
      return Promise.reject(response.data)
    }
  },
  error => {
    // 捕获服务器返回的状态码
    if (error && error.response) {
      Notification({ type: 'error', title: 'error', message: throwErr(error.response.status, error.response) || 'error' })
      return Promise.reject(error)
    }
    // 捕获设置的超时时间
    if (error.message.includes('timeout')) {
      Notification({ type: 'error', title: 'error', message: 'Network timeout' })
      return Promise.reject(error)
    }
    return Promise.reject(error)
  }
)
// 请求方法
export default function request (method, url, data) {

  method = method.toLocaleLowerCase()
  if (method === 'post') {
    return axios.post(server + url, data)
  } else if (method === 'put') {
    return axios.put(server + url, data)
  } else if (method === 'get') {
    return axios.get(server + url, {
      params: data
    })
  } else if (method === 'delete') {
    return axios.delete(server + url, {
      params: data
    })
  }
}
export const httpServer = server

